﻿package com.woniuxy.servlet;

import java.io.IOException;
import java.lang.reflect.Method;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")
public class BaseServlet extends HttpServlet {
	@Override
	public void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		//响应乱码
		response.setContentType("text/html;charset=UTF-8");
		//post请求乱码
		request.setCharacterEncoding("UTF-8");
		//获取method请求参数，他的值就是要调用的方法名
		String methodName = request.getParameter("method");
		Method method = null;

		try {
			/*
			 * this是当前的servlet
			 * 当前servlet中获取方法名为methodName的方法对象
			 */
			method = this.getClass().getMethod(methodName, 
					HttpServletRequest.class, HttpServletResponse.class);
		} catch (Exception e) {
			throw new RuntimeException("您要调用的方法：" + methodName + "它不存在！", e);
		}

		try {
			
			/**
			 * 调用要请求的methodName方法,这个方法的返回值是String
			 * 这个方法的返回值就是转发或者重定向的路径
			 * 在返回值中找：
			 * result=":";
			 */
			String result = (String) method.invoke(this, request, response);
			if (result != null && !result.trim().isEmpty()) {
				//查找:的下标
				int index = result.indexOf(":");
				//没有:
				//默认转发 result="/a.jsp"
				if (index == -1) {
					request.getRequestDispatcher(result).forward(request, response);
				} else {
					//有:
					//有两种，第一种 result="f:/a.jsp";  第二种 result="r:/a.jsp";
 					String start = result.substring(0, index);
					String path = result.substring(index + 1);
					if (start.equals("f")) {
						// 如果是这种 result="f:/a.jsp"; 就是转发
						request.getRequestDispatcher(path).forward(request, response);
					} else if (start.equals("r")) {
						//如果是 result="r:/a.jsp"; 重定向
						response.sendRedirect(request.getContextPath() + path);
					}else if(start.equals("i")) {
						//如果是 result="i:/a.jsp"; 请求包含
						request.getRequestDispatcher(path).include(request, response);
					}
				}
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}
